﻿using AutoMapper;
using Ccteg.Common;
using Ccteg.DB;
using LinqKit;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using Quartz;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Threading.Tasks;

namespace Ccteg.JobHostQuartz
{
    //防止运行多个相同的任务实例
    [DisallowConcurrentExecution]
    public class WorkService : IJob
    {

        public IServiceProvider _serviceProvider;
        public IServiceProvider GetServiceProvider(IJobExecutionContext context)
        {

            if (_serviceProvider == null)
            {
                var service = context.JobDetail.JobDataMap["IServiceProvider"] as IServiceProvider;
                _serviceProvider = service;

            }
            return _serviceProvider;

        }
        public async Task Execute(IJobExecutionContext context)
        {
            string dataType = context.JobDetail.JobDataMap.GetString("jobType");
            using (var serviceScope = GetServiceProvider(context).CreateScope())
            {

                var _dbContext = serviceScope.ServiceProvider.GetService<MySqlDbContext>();
                using (_dbContext)
                {
                    Expression<Func<sfm_job, bool>> where = p => true;
                    where = where.CheckNullAnd(x => x.DataType == dataType, dataType);
                    where = where.And(x => x.Status == 0);

                    var list = _dbContext.Sfm_Job.AsQueryable().Where(where.Expand()).OrderByDescending(x => x.Id).ToList();
                    foreach (sfm_job job in list)
                    {
                        var res = KafakHelper.Producer(job.Topic, job.JsonData);
                        var entity = _dbContext.Sfm_Job.FirstOrDefault(x => x.Id == job.Id);
                        if (res.Code == 200)
                        {
                            entity.Status = 1;
                            entity.Sendtime = DateTime.Now;
                        }
                        else
                        {
                            entity.Status = 2;
                            entity.Sendtime = DateTime.Now;
                            entity.ExMesagge = res.Message;
                        }
                        _dbContext.SaveChanges();
                    }
                }
            }
        }
    }
}
